<template>
  <div class="app-container">
    <el-tabs v-model="tabActiveName" type="card">
      <el-tab-pane label="卡片基本信息" name="basicInfo">
        <div class="form-item">卡片信息</div>
        <el-form :model="recordInfo" label-width="140px">
          <el-row>
            <el-col :span="8">
              <el-form-item label="权益卡名称：" required>
                <el-input v-model="recordInfo.benefCardNm" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="18">
              <el-form-item label="权益卡副标题：">
                <el-input v-model="recordInfo.slogan" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="卡片封面：" required>
                <el-upload
                  ref="cardImage"
                  accept=".png, .jpg, .jpeg"
                  class=""
                  :limit="2"
                  action="#"
                  :auto-upload="false"
                  :show-file-list="false"
                  :on-change="changeCardImage"
                >
                  <div class="uploader">
                    <img :src="cardImage" class="image1">
                  </div>
                  <el-button type="primary" class="select-image-button">选择图片</el-button>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="卡片服务电话：" required>
                <el-input v-model="recordInfo.servTel" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="售价：" required>
                <el-input v-model="recordInfo.salesPrice" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="卡片有效期：" required>
            <el-radio-group v-model="recordInfo.cardValidType">
              <el-row>
                <el-radio :label="0">永久有效</el-radio>
              </el-row>
              <el-row>
                <el-radio :label="1">
                  <span>领取后</span>
                  <el-input
                    v-model="recordInfo.validDays"
                    :disabled="1!==recordInfo.cardValidType"
                    :min="1"
                    type="number"
                    style="width: 120px;margin: 0 6px;"
                  />
                  <span style="color: black;">天内有效</span>
                </el-radio>
              </el-row>
              <el-row>
                <el-radio :label="2">指定时间：
                  <el-date-picker
                    v-model="validTm"
                    :disabled="2!==recordInfo.cardValidType"
                    type="daterange"
                    value-format="timestamp"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                  />
                </el-radio>
              </el-row>
            </el-radio-group>
          </el-form-item>
          <div class="form-item">权益卡：包含的权益</div>
          <el-form-item label="优惠券：">
            <div>
              <span class="add-coupon-btn" @click="addCoupon">选择优惠券</span>
            </div>
            <el-table class="table-default" :data="couponList">
              <el-table-column label="优惠券名称" prop="activityName" align="center" />
              <el-table-column label="优惠券类型" prop="couponType" width="140" show-tooltip-when-overflow align="center" />
              <el-table-column label="用券时间" prop="time" width="120" align="center" />
              <el-table-column label="是否启用" prop="state" width="50" align="center" />
              <el-table-column label="创建时间" prop="createTime" width="140" align="center" />
              <el-table-column label="操作" width="150" align="center">
                <template v-slot="scope">
                  <el-button type="danger" size="small" @click="removeCoupon(scope.$index)">移除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="权益卡介绍" name="detailImage">
        <el-row :gutter="20">
          <el-col :span="12" style="border-right: solid 1px #999;padding-right: 30px">
            <el-form ref="ruleForm" label-width="100px" class="demo-ruleForm">
              <el-form-item label="介绍图：">
                <drag-multiple-img
                  :pictures.sync="descriptionImageList"
                  :multiple="false"
                  @add="descriptionImageAddPictureEvent"
                  @delete="descriptionImageListPicture "
                />
                <p style="margin: 0;"><span style="color:red;">*</span>请上传800*800px，大小不超过2M</p>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="12" style="padding-left: 30px">
            <div class="preview-item">
              <div class="header">页面预览</div>
              <div class="box-card">
                <div class="item">
                  <el-image v-for="(item, index) in descriptionImageList" :key="index" :src="getImgUrl(item)">
                    <div slot="placeholder" class="image-slot">
                      加载中<span class="dot">...</span>
                    </div>
                    <div slot="error" class="image-slot" />
                  </el-image>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>
    <el-button type="warning" class="save-btn" @click="save">保存</el-button>
    <el-dialog title="选择优惠券" width="80%" :visible.sync="showSelectCoupon" top="5vh" :close-on-click-modal="false">
      <el-form :inline="true">
        <el-form-item label="优惠券名称：">
          <el-input v-model="selectCouponObject.queryForm.activityName" placeholder="优惠券名称" clearable />
        </el-form-item>
        <el-form-item label="优惠券类型：">
          <el-select v-model="selectCouponObject.queryForm.marketingParamType" filterable placeholder="请选择" clearable>
            <el-option label="满减券" :value="0" />
            <el-option label="商品兑换券" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchCoupon">搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addCouponToList">添加</el-button>
        </el-form-item>
      </el-form>
      <el-table
        ref="multipleTable"
        key="index"
        v-loading="selectCouponObject.loading"
        class="table-default"
        :data="selectCouponObject.list"
        border
        @selection-change="selectCoupon"
      >
        <el-table-column type="selection" width="43" align="center" fixed="left" />
        <el-table-column label="优惠券名称" prop="activityName" align="center" />
        <el-table-column label="优惠券类型" width="100" prop="couponType" show-tooltip-when-overflow align="center" />
        <el-table-column label="用券时间" prop="useTime" width="120" align="center" />
        <el-table-column label="创建时间" prop="createTime" width="140" align="center" />
      </el-table>
      <el-pagination
        style="margin-top: 10px;"
        background
        :current-page.sync="selectCouponObject.queryForm.page"
        :page-size.sync="selectCouponObject.queryForm.pageSize"
        :page-sizes="[5,10,20,30,50,100,200,500]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="selectCouponObject.total"
        @size-change="changeSelectCouponPageSize"
        @current-change="changeSelectCouponPage"
      />
    </el-dialog>
  </div>
</template>

<script>
import locationMixin from '@/mixins/modules/location'
import iframeMessageMixin from '@/mixins/modules/iframeMessage'
import filters from '@/filters/index'
import dragMultipleImg from '@/components/FileUpload/dragMultiplelmg.vue'

let hasChangeImageList = false

export default {
  components: {
    dragMultipleImg
  },
  filters: {
    ...filters
  },
  mixins: [locationMixin, iframeMessageMixin],
  data() {
    return {
      showSelectCoupon: false,
      selectCouponObject: {
        queryForm: {
          activityName: '',
          marketingParamType: 1,
          appId: 4,
          marketingType: 8,
          returnCount: false,
          orderBy: 'createTimeDesc',
          page: 1,
          pageSize: 5
        },
        loading: false,
        total: 0,
        list: [],
        selectedList: []
      },
      validTm: null,
      cardImage: '',
      cardImageFile: undefined,
      couponList: [],
      tabActiveName: 'basicInfo',
      descriptionImageList: [],
      deleteFileList: [],
      recordInfo: {
        benefCardNm: '',
        slogan: '',
        servTel: '',
        salesPrice: '',
        cardValidType: 0,
        validDays: 0,
        validStartTm: undefined,
        validEndTm: undefined,
        cardShowType: 0,
        cardGrantType: 0,
        cardGrantNum: 0,
        cardIntrod: '',
        protocol: 1,
        st: 0
      }
    }
  },
  computed: {},
  created() {
    const query = this.$route.query
    if (undefined !== query.params) {
      const params = JSON.parse(decodeURIComponent(this.$Base64.decode(query.params)))
      this.recordInfo = {
        ...this.recordInfo,
        ...params
      }
      this.action = params.action
      if (undefined !== this.recordInfo.benefCardId) {
        this.getData()
      }
    }
  },
  methods: {
    getImgUrl(item) {
      let imgUrl = ''
      if (undefined !== item.fileUrl) {
        imgUrl = item.fileUrl
      } else if (undefined !== item.downloadCode) {
        imgUrl = this.$api.getDownloadServiceUrl(item.downloadCode)
      }
      return imgUrl
    },
    descriptionImageAddPictureEvent() {
      hasChangeImageList = true
    },
    descriptionImageListPicture(event) {
      this.$confirm('是否删除此图片?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        for (let i = 0; i < this.descriptionImageList.length; i++) {
          if (this.descriptionImageList[i].oldIndex === event.oldIndex) {
            this.descriptionImageList.splice(i, 1)
          }
        }
        hasChangeImageList = true
        this.deleteFileList.push(event.otherFileId)
      }).catch(() => {})
    },
    addCoupon() {
      this.showSelectCoupon = true
      if (this.selectCouponObject.list.length === 0) {
        this.searchCoupon()
      }
    },
    selectCoupon(d) {
      this.selectCouponObject.selectedList = d
    },
    changeSelectCouponPageSize(e) {
      this.selectCouponObject.queryForm.pageSize = e
      this.searchCoupon()
    },
    changeSelectCouponPage(e) {
      this.selectCouponObject.queryForm.page = e
      this.searchCoupon()
    },
    searchCoupon() {
      this.selectCouponObject.loading = true
      this.selectCouponObject.queryForm.returnCount = this.selectCouponObject.queryForm.page === 1
      this.$api.getMarketingActivityList(this.selectCouponObject.queryForm, undefined).then(res => {
        this.selectCouponObject.loading = false
        if (undefined === res.list || res.list.length === 0) {
          this.selectCouponObject.list = []
          this.selectCouponObject.total = 0
          return
        }
        for (let i = 0; i < res.list.length; i++) {
          if (res.list[i].marketingParamType === 1) {
            res.list[i].couponType = '商品兑换券'
          } else {
            res.list[i].couponType = '满减券'
          }
          res.list[i].createTime = this.$commonUtils.getShowTime(res.list[i].createTime)
        }
        if (this.selectCouponObject.queryForm.page === 1) {
          this.selectCouponObject.total = parseInt(res.count)
        }
        this.selectCouponObject.list = res.list
      }, _ => {
        this.selectCouponObject.loading = false
      })
    },
    addCouponToList() {
      let inList
      for (let i = 0; i < this.selectCouponObject.selectedList.length; i++) {
        // 排除重复的
        inList = false
        for (let j = 0; j < this.couponList.length; j++) {
          if (this.couponList[j].marketingActivityId === this.selectCouponObject.selectedList[i]
            .marketingActivityId) {
            inList = true
            break
          }
        }
        if (inList === false) {
          this.couponList.push(this.selectCouponObject.selectedList[i])
        }
      }
      this.showSelectCoupon = false
    },
    removeCoupon(index) {
      this.couponList.splice(index, 1)
    },
    changeCardImage(file) {
      this.cardImageFile = file
      this.$refs.cardImage.clearFiles()
      const imgSize = 1024 // 1M
      if (file.size / 1024 > imgSize) {
        return this.$commonUtils.showErrorToast('上传图片不大于1M')
      }
      this.cardImage = ''
      // 预览图片,转为base64
      const reader = new FileReader()
      const that = this
      reader.readAsDataURL(file.raw)
      reader.onload = function(e) {
        that.cardImage = this.result
      }
    },
    async getData() {
      try {
        let res = await this.$api.getBenefitCardDetail({
          benefCardId: this.recordInfo.benefCardId
        })
        res.salesPrice = this.$amountUtils.getYuan(res.salesPrice)
        const benefitCardItemVOList = res.benefitCardItemVOList
        if (undefined !== benefitCardItemVOList && benefitCardItemVOList.length > 0) {
          for (let i = 0; i < benefitCardItemVOList.length; i++) {
            if (benefitCardItemVOList[i].relatType === 8) {
              const marketingActivityVO = benefitCardItemVOList[i].marketingActivityVO
              if (marketingActivityVO) {
                const marketingParamType = marketingActivityVO.marketingParamType
                let couponType = ''
                switch (marketingParamType) {
                  case 0:
                    couponType = '满减券'
                    break
                  case 1:
                    couponType = '商品兑换券'
                    break
                  default:
                    couponType = '未知类型'
                    break
                }
                const item = {
                  ...marketingActivityVO,
                  couponType,
                  activityName: marketingActivityVO.activityName,
                  marketingActivityId: benefitCardItemVOList[i].relatId,
                  createTime: this.$commonUtils.getShowTime(marketingActivityVO.createTime)
                }
                // 优惠券
                this.couponList.push(item)
              }
            }
          }
        }
        this.validTm = [res.validStartTm, res.validEndTm]
        this.recordInfo = res
        // 加载相关图片
        res = await this.$api.getOtherFileList({
          relatId: this.recordInfo.benefCardId
        })
        if (undefined !== res.list && res.list.length > 0) {
          this.descriptionImageList = []
          for (let i = 0; i < res.list.length; i++) {
            if (res.list[i].fileSort === 1) {
              // 权益卡背景图
              this.cardImage = this.$api.getDownloadServiceUrl(res.list[i].fileDownloadCode)
            } else if (res.list[i].fileSort === 2) {
              this.descriptionImageList.push({
                downloadCode: res.list[i].fileDownloadCode,
                otherFileId: res.list[i].otherFileId,
                oldIndex: i
              })
            }
          }
          this.$forceUpdate()
        }
      } catch (err) {
        console.error(err)
      }
    },
    async save() {
      try {
        if (this.recordInfo.benefCardNm === '') {
          return this.$message({
            type: 'warning',
            message: '请填写权益卡名称'
          })
        }
        const params = {
          ...this.recordInfo
        }
        if (this.validTm !== null) {
          params.validStartTm = this.validTm[0]
          params.validEndTm = this.validTm[1]
        } else {
          params.validStartTm = 0
          params.validEndTm = 0
        }
        if (this.recordInfo.salesPrice !== '') {
          params.salesPrice = (this.recordInfo.salesPrice * 100).toFixed(0)
        } else {
          params.salesPrice = 0
        }
        if (this.couponList.length > 0) {
          params.benefitCardItemVOList = []
          for (let i = 0; i < this.couponList.length; i++) {
            params.benefitCardItemVOList.push({
              relatId: this.couponList[i].marketingActivityId,
              relatType: 8
            })
          }
        }
        if (undefined === this.recordInfo.benefCardId) {
          const res = await this.$api.addBenefitCard(params, undefined !== this.cardImageFile && this
            .cardImageFile !== null ? this.cardImageFile.raw : undefined)
          this.recordInfo.benefCardId = res.id
          this.$message({
            type: 'success',
            message: '创建成功'
          })
        } else {
          await this.$api.updateBenefitCard(params, undefined !== this.cardImageFile && this
            .cardImageFile !== null ? this.cardImageFile.raw : undefined)
          this.$message({
            type: 'success',
            message: '保存成功'
          })
        }
        // 保存介绍图片
        if (hasChangeImageList === true) {
          const filesParam = {
            list: []
          }
          const files = []
          for (let i = 0; i < this.descriptionImageList.length; i++) {
            if (undefined !== this.descriptionImageList[i].file && this.descriptionImageList[i].file !== '') {
              files.push(this.descriptionImageList[i].file)
              filesParam.list.push({
                fileSort: 2,
                relatId: this.recordInfo.benefCardId,
                ordNum: i
              })
            }
          }
          if (files.length > 0) {
            // 有新增加的图片
            await this.$api.batchAddOtherFile(filesParam, files)
          }
          if (this.deleteFileList.length > 0) {
            // 有删除的图片
            for (let i = 0; i < this.deleteFileList.length; i++) {
              await this.$api.deleteOtherFile({
                otherFileId: this.deleteFileList[i]
              }, {
                showLoading: false
              })
            }
          }
        }
        this.sendCloseTabMessage()
      } catch (err) {
        console.error(err)
      }
    },
    editClick(item) {
      this.$addTab('basicArchivesStaffEdit', {
        action: 'edit',
        userId: this.recordInfo.adminUserId
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .app-container {
    .input-width {
      width: 300px;
    }

    .img-upload-container {
      width: 150px;
      height: 213px;
      padding: 6px;
      text-align: center;
      border: 1px solid #ececec;
      position: relative;
      margin: 0 10px 10px 0;

      .el-button {
        width: 140px;
      }

      .delete-ico {
        position: absolute;
        right: 4px;
        top: 4px;
        color: red;
        display: none;
      }

      ::v-deep .action-label {
        .el-icon-delete {
          display: none;
        }
      }
    }

    .img-upload-container:hover {
      .delete-ico {
        display: inline;
      }
    }

    .img-upload-add-container {
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28px;
      color: #666666;
    }

    .save-btn {
      position: fixed;
      top: 10px;
      right: 10px;
    }

    .repeat-organization-view {
      z-index: 1000;
      position: fixed;
      display: flex;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      align-items: center;
      justify-content: center;
      background-color: rgba(0, 0, 0, .3);

      .repeat-organization-content {
        width: 35%;
        box-shadow: 0 0 10px 0px #000;
        background-color: #fff;
        padding: 10px;
        border-radius: 10px;

        .title {
          color: #f00;
          font-size: 18px;
          font-weight: bold;
          height: 60px;
          line-height: 60px;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .item {
          padding: 10px;
          border-bottom: 1px #eee dotted;

          .name {
            font-size: 16px;
            font-weight: bold;
          }

          .address {
            color: #aaa;
            margin-top: 10px;
          }
        }

        .button-view {
          height: 60px;
          display: flex;
          align-items: center;
          justify-content: center;

          .button {
            width: 120px;
            margin-left: 10px;
            margin-right: 10px;
          }
        }
      }
    }
  }

  .uploader {
    display: flex;
    align-items: center;

    .select-image-button {
      margin-left: 5px;
    }

    .image1 {
      width: 300px;
      height: 100px;
    }
  }

  .form-item {
    font-weight: bold;
    padding: 20px 20px;
    margin-bottom: 30px;
    border-bottom: 1px solid #DCDFE6;
  }

  .add-coupon-btn {
    // margin-left: 30px;
    margin-right: 30px;
    color: #409EFF;
    cursor: pointer;
  }
</style>
